package com.aiwei.tdjk.service.impl;

import com.aiwei.tdjk.dao.extend.JobExtendMapper;
import com.aiwei.tdjk.entity.Job;
import com.aiwei.tdjk.entity.JobExample;
import com.aiwei.tdjk.service.JobService;
import com.google.common.collect.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * Created by yanfeng on 2016/12/13.
 */
@Service
public class JobServiceImpl implements JobService {

    @Autowired
    private JobExtendMapper jobExtendMapper;

    @Override
    public Set<Long> findAncestorIds(Iterable<Long> currentIds) {
        Set<Long> parents = Sets.newHashSet();
        for (Long currentId : currentIds) {
            parents.addAll(findAncestorIds(currentId));
        }
        return parents;
    }

    @Override
    public Set<Long> findAncestorIds(Long currentId) {
        Set ids = Sets.newHashSet();

        Job job = jobExtendMapper.selectByPrimaryKey(currentId);

        if (job == null) {
            return ids;
        }
        for (String idStr : StringUtils.tokenizeToStringArray(job.getParentIds(), "/")) {
            if (!StringUtils.isEmpty(idStr)) {
                ids.add(Long.valueOf(idStr));
            }
        }
        return ids;
    }

    /**
     * 过滤仅获取可显示的数据
     *
     * @param jobIds
     * @param organizationJobIds
     */
    public void filterForCanShow(Set<Long> jobIds, Set<Long[]> organizationJobIds) {

        Iterator<Long> iter1 = jobIds.iterator();

        while (iter1.hasNext()) {
            Long id = iter1.next();
            Job o = jobExtendMapper.selectByPrimaryKey(id);
            if (o == null || Boolean.FALSE.equals(o.getIsShow())) {
                iter1.remove();
            }
        }

        Iterator<Long[]> iter2 = organizationJobIds.iterator();

        while (iter2.hasNext()) {
            Long id = iter2.next()[1];
            Job o = jobExtendMapper.selectByPrimaryKey(id);
            if (o == null || Boolean.FALSE.equals(o.getIsShow())) {
                iter2.remove();
            }
        }

    }


    /**
     * 查询all组织机构
     *
     * @return
     */
    @Override
    public List<Job> findAllWithSort(boolean isShow) {
        JobExample example = new JobExample();
        if(isShow){
            example.or().andIsShowEqualTo(true);
        }else {
            example.or();
        }
        example.setOrderByClause("parent_ids asc, weight asc");
        return jobExtendMapper.selectByExample(example);
    }

    /**
     * 根据名称模糊查询组织机构
     * @param name
     * @return
     */
    @Override
    public List<Job> findAllByName(String name) {
        return jobExtendMapper.findAllByName(name);
    }

    /**
     * 新增子节点
     *
     * @param parentId
     * @param child
     */
    @Override
    public void appendChild(long parentId, Job child) {
        child.setParentId(parentId);
        Job parent = jobExtendMapper.selectByPrimaryKey(parentId);
        child.setParentIds(parent.getParentIds()+parent.getId()+"/");
        child.setWeight(nextWeight(parent.getId()));
        child.setIsShow(true);
        jobExtendMapper.insertSelective(child);
    }

    /**
     * 删除节点
     *
     * @param id
     */
    @Override
    public void delete(long id) {
        jobExtendMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void deleteSelfAndChild(long id, String makeSelfAsNewParentIds) {
        jobExtendMapper.deleteSelfAndChild(id,makeSelfAsNewParentIds);
    }

    /**
     * 根据主键id获取元素
     *
     * @param id
     * @return
     */
    @Override
    public Job get(long id) {
        return jobExtendMapper.selectByPrimaryKey(id);
    }

    /**
     * 更新节点
     *
     * @param job
     */
    @Override
    public void update(Job job) {
        String str = job.getParentIds();
        boolean lang= job.getIsShow();
        if (!lang) {
            updateChildIsShow(lang,str + job.getId());
        } else {
            while (str!=""){
                str=getSubStr(str);
                if(str.equals("")) break;
                updateChildIsShow(lang,str);
            }
        }
        jobExtendMapper.updateByPrimaryKey(job);
    }

    /**
     * 修改子节点状态
     *
     * @param parentIds
     * @return
     */
    public void updateChildIsShow(boolean isShow,String parentIds) {
        Job job =new Job();
        job.setIsShow(isShow);
        job.setParentIds(parentIds);
        jobExtendMapper.updateChildIsShow(job);
    }

    public String getSubStr(String str) {
        str=str.substring(0,str.lastIndexOf("/"));
        str=str.substring(0,str.lastIndexOf("/")+1);
        return str;
    }

    //"select case when max(weight) is null then 1 else (max(weight) + 1) end from %s where parentId = ?1"
    public int nextWeight(long id) {
        JobExample example = new JobExample();
        example.or().andParentIdEqualTo(id);
        example.setOrderByClause("weight Desc");
        List<Job> organizations = jobExtendMapper.selectByExample(example);
        if (organizations.isEmpty()){
            return 1;
        }else{
            return organizations.get(0).getWeight()+1;
        }
    }
    /**
     * 根据用户的id查询该用户是否有改工作职务
     * @param jobName 工作名字
     * @param userId 登录用户的id
     * @return
     */
    @Override
    public boolean findJobCountByUserId(String jobName,Long userId){
        int row = jobExtendMapper.findJobCountByUserId(jobName,userId);
        if(row>0){
            return true;
        }
        return false;
    }
}
